<template>
  <div class="all">
    <el-page-header title="返回" @back="goBack" content="输入提取码提取文件">
    </el-page-header>
    <div class="container">
      <div class="card">
        <el-card>
          <div class="card-header">
            <div class="card-header-user-info">
              <div class="card-header-user-info-avatar">
                <el-avatar icon="el-icon-user-solid"></el-avatar>
              </div>
              <div class="card-header-user-info-box">
                <p
                  style="
                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  {{ fileUrl.userName }}
                </p>
              </div>
            </div>
          </div>
          <div class="card-body">
            <div class="card-body-text">
              <p>请输入提取码：</p>
            </div>
            <div class="card-body-extract">
              <el-input
                style="width: 280px; border: 1px solid #f2f2f2"
                v-model="code"
              ></el-input>
              <el-button
                round
                type="primary"
                style="margin-left: 14px"
                @click="handleExtract"
                >提取文件</el-button
              >
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script>


import request from "@/utils/request";
import api from "@/api/system/fileUrl";
import fileApi from "@/api/system/file";
export default {
  data() {
    return {
      downloadingFileList: [],
      code: "",
      fileUrl: {},
      file: {},
    };
  },
  async created() {
    await api.findById(this.$route.query.urlId).then((response) => {
      this.fileUrl = response.data;
      console.log(this.fileUrl);
    });
    await fileApi.getUserId(this.fileUrl.fileId).then((response) => {
      this.file = response.data;
      console.log(this.file);
    });
    this.$forceUpdate();
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    handleExtract() {
        this.downloadFile(this.file);
    },
    //下载文件
    formatSize(file) {
      //console.log("size",file.size);
      var size = file.size;
      var unit;
      var units = [" B", " K", " M", " G"];
      var pointLength = 2;
      while ((unit = units.shift()) && size > 1024) {
        size = size / 1024;
      }
      return (
        (unit === "B"
          ? size
          : parseFloat(size).toFixed(
              pointLength === undefined ? 2 : pointLength
            )) + unit
      );
    },
    changeDownloadStop(file) {
      file.downloadingStop = !file.downloadingStop;
      if (!file.downloadingStop) {
        console.log("开始。。");
        this.downloadChunk(1, file);
      }
    },

    downloadFile(file) {
      console.log("下载", file);
      file.downloadingStop = false;
      file.downloadSpeed = "0 M/s";
      file.downloadPersentage = 0;
      file.blobList = [];
      file.chunkList = [];
      this.downloadingFileList.push(file);

      this.downloadChunk(1, file);
    },

    downloadChunk(index, file) {
      var chunkSize = 1024 * 1024 * 5;
      var chunkTotal = Math.ceil(file.size / chunkSize);
      console.log(file);
      if (index <= chunkTotal) {
        // console.log("下载进度",index);
        var exit = file.chunkList.includes(index);
        // console.log("存在", exit);

        if (!exit) {
          if (!file.downloadingStop) {
            var formData = new FormData();
            formData.append("fileName", file.fileName);
            formData.append("md5", file.md5);
            formData.append("chunkSize", chunkSize);
            formData.append("index", index);
            formData.append("chunkTotal", chunkTotal);
            if (index * chunkSize >= file.size) {
              chunkSize = file.size - (index - 1) * chunkSize;
              formData.set("chunkSize", chunkSize);
            }

            var startTime = new Date().valueOf();

            request({
              url: "/common/download",
              method: "post",
              data: formData,
              responseType: "blob",
              timeout: 50000,
            }).then((res) => {
              console.log("开始下载第" + index + "个分片");

              file.chunkList.push(index);

              var endTime = new Date().valueOf();
              var timeDif = (endTime - startTime) / 1000;
              file.downloadSpeed = 5 / timeDif + " M/s";
              //todo
              file.downloadPersentage = parseInt((index / chunkTotal) * 100);
              // var chunk = res.data.data.chunk
              // const blob = new Blob([res.data]);
              const blob = res;
              file.blobList.push(blob);
              console.log(file.blobList);
              if (index == chunkTotal) {
                var resBlob = new Blob(file.blobList, {
                  type: "application/octet-stream",
                });
                console.log("resb", resBlob);

                let url = window.URL.createObjectURL(resBlob); // 将获取的文件转化为blob格式
                console.log(url);
                let a = document.createElement("a"); // 此处向下是打开一个储存位置
                a.style.display = "none";
                a.href = url;
                // 下面两行是自己项目需要的处理，总之就是得到下载的文件名（加后缀）即可

                var fileName = file.fileName;
                console.log("down" + file.fileName);
                a.setAttribute("download", fileName);
                document.body.appendChild(a);
                a.click(); //点击下载
                document.body.removeChild(a); // 下载完成移除元素
                window.URL.revokeObjectURL(url); // 释放掉blob对象
              }

              this.downloadChunk(index + 1, file);
            });
          }
        } else {
          file.downloadPersentage = parseInt((index / chunkTotal) * 100);
          this.downloadChunk(index + 1, file);
        }
      }
    },
  },
};
</script>
<style>
.all {
  margin-top: 15%;
  margin-left: 35%;
}

.container {
  width: 460px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-right: 35px;
}

.share-extract-card-body {
  padding: 20px 30px 48px;
}

.card-header-user-info {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.card-body-extract {
  display: flex;
  align-items: center;
}
</style>